import {
	Button,
	Collapse,
	Form,
	Input,
	Row,
	Col,
	TreeSelect,
	message,
	Select,
} from 'antd'
import React, {memo, useEffect, useState} from 'react'
import {history, connect} from 'umi'
import styles from '@/assets/common/css/page.less'
import {getDict} from '@/service/common/dict'
import {
	addCompany,
	editCompany,
	viewCompany,
	getCompanyScope,
	getParentMerchant,
} from '@/service/system/company'
import {translateDataToTree} from '@/utils/common/index'

const {TextArea} = Input
const {Panel} = Collapse

const companyDom = memo(
	(props: {user: any; location: {query: {id: any; cid: any}}}) => {
		const {currentMerchantId} = props.user
		const {id, cid} = props.location.query
		const [type, setType] = useState<string>()
		const [treeData, setTreeData] = useState<any[]>([])
		const [form] = Form.useForm()
		const [idData, setIdData] = useState('')
		const [dict, setDict] = useState<any>({
			Company_Main_Type: [],
		})
		useEffect(() => {
			getDict(
				{
					dictKeys: ['Company_Main_Type'],
				},
				(res: any) => {
					setDict(res)
				},
			)
		}, [])

		// 获取上级组织
		const onCompanyFun = () => {
			getCompanyScope({merchantId: currentMerchantId}).then(
				(res: any) => {
					if (res?.success) {
						const list = translateDataToTree(res.data)
						getParentMerchant({
							merchantId: currentMerchantId,
						}).then((r: any) => {
							if (r?.success) {
								if (
									!cid &&
									id?.toString() ===
										currentMerchantId?.toString()
								) {
									setTreeData([
										{
											...r.data,
											children: [...list],
										},
									] as any)
								} else {
									setTreeData(() => list)
								}
							}
						})
					}
				},
			)
		}
		const onViewFun = (merchantId: string) => {
			viewCompany(merchantId).then((res: any) => {
				if (res?.success) {
					form.setFieldsValue({
						...res?.data,
						type: res?.data?.type?.toString(),
						parentId:
							res?.data?.parentId === 0
								? '根节点'
								: res?.data?.parentId,
					})
				}
			})
		}

		useEffect(() => {
			if (currentMerchantId) {
				onCompanyFun()
			}
		}, [currentMerchantId, id, cid])

		useEffect(() => {
			const hrefs = window.location.href
			if (hrefs.includes('view')) {
				setType('view')
			} else {
				setType('edit')
			}
			if (!id && (cid || cid === 0)) {
				form.setFieldsValue({parentId: cid})
			}
			if (id) {
				setIdData(id)
				onViewFun(id)
			}
		}, [id, cid])
		// 表单提交
		const onFinish = async () => {
			const fromData = await form.validateFields()
			if (!idData) {
				// 新增公司
				addCompany({...fromData})
					.then((res: any) => {
						if (res?.success) {
							message.success(res.msg)
							history.goBack()
						}
					})
					.catch((err) => {
						message.error(err)
					})
			} else {
				editCompany({...fromData}, idData)
					.then((res: any) => {
						if (res?.success) {
							message.success(res.msg)
							history.goBack()
						}
					})
					.catch((err) => {
						message.error(err)
					})
			}
		}
		const customizeHeader = (value: string) => (
			<div>
				<div className={styles.tip} />
				{value}
			</div>
		)
		return (
			<div className={styles.page}>
				<div className={`${styles.content} ${styles.formDetils}`}>
					<Collapse
						defaultActiveKey={['1']}
						ghost
						expandIconPosition="end">
						<Panel header={customizeHeader('基础信息')} key="1">
							<Form
								name="basic"
								form={form}
								layout="horizontal"
								labelCol={{style: {width: 80}}}
								initialValues={{remember: true}}
								disabled={type === 'view'}
								autoComplete="off">
								<Row gutter={12}>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="名称"
											name="name"
											rules={[
												{
													required: true,
													message: '请输入名称',
												},
											]}>
											<Input
												placeholder="请输入名称"
												maxLength={60}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="上级组织"
											name="parentId"
											rules={[
												{
													required: true,
													message: '请输入上级组织',
												},
											]}>
											<TreeSelect
												showSearch
												style={{width: '100%'}}
												dropdownStyle={{
													maxHeight: 400,
													overflow: 'auto',
												}}
												placeholder="请选择公司"
												allowClear
												treeNodeFilterProp="label"
												treeDefaultExpandAll
												fieldNames={{
													label: 'name',
													value: 'id',
												}}
												treeDataSimpleMode
												treeData={treeData}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item label="公司类型" name="type">
											<Select
												placeholder="请选择公司类型"
												fieldNames={{
													value: 'dictKey',
													label: 'dictValue',
												}}
												options={[
													...dict.Company_Main_Type,
												]}
											/>
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="描述"
											name="description">
											<TextArea
												placeholder="请输入（最多200个字）"
												autoSize={{
													minRows: 4,
													maxRows: 6,
												}}
												maxLength={200}
											/>
										</Form.Item>
									</Col>
								</Row>
							</Form>
						</Panel>
					</Collapse>
					<div className={styles.wrap}>
						{type !== 'view' ? (
							<Button
								type="primary"
								htmlType="submit"
								onClick={onFinish}>
								保存
							</Button>
						) : null}
						<Button
							htmlType="reset"
							className="reset"
							onClick={(e) => {
								e.stopPropagation()
								history.goBack()
							}}>
							取消
						</Button>
					</div>
				</div>
			</div>
		)
	},
)
export default connect(({user}: any) => ({user}))(companyDom)
